package com.bhs.sansonglogistics.dialog;

import static android.app.AlertDialog.THEME_DEVICE_DEFAULT_LIGHT;

import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.DatePicker;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bhs.sansonglogistics.R;
import com.bhs.sansonglogistics.base.BaseActivity;
import com.bhs.sansonglogistics.base.BaseFragment;
import com.bhs.sansonglogistics.bean.DedicatedLineBean;
import com.bhs.sansonglogistics.bean.DedicatedLineDataBean;
import com.bhs.sansonglogistics.bean.TabBean;
import com.bhs.sansonglogistics.bean.event.ScreenEvent;
import com.bhs.sansonglogistics.net.NetCallBack;
import com.bhs.sansonglogistics.ui.adapter.ScreenAdapter;
import com.bhs.sansonglogistics.utils.DateUtils;
import com.bhs.sansonglogistics.utils.LogUtils;
import com.bhs.sansonglogistics.utils.MyUtils;
import com.bhs.sansonglogistics.utils.ToastUtil;
import com.bhs.sansonglogistics.view.AutoLineFeedLayoutManager;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.loper7.date_time_picker.DateTimeConfig;
import com.loper7.date_time_picker.dialog.CardDatePickerDialog;
import com.lxj.xpopup.core.BottomPopupView;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import okhttp3.ResponseBody;
import retrofit2.Response;

/**
 * 订单筛选
 */
public class ScreenDialog extends Dialog implements NetCallBack, View.OnClickListener {
    private LinearLayout mLlScreen;
    private LinearLayout mLlTime;
    private TextView mTvStartTime;
    private TextView mTvEndTime;
    private RecyclerView mRvLine;

    private RecyclerView mRvType;
    private ScreenAdapter typeAdapter;
    private final List<TabBean> typeList = new ArrayList<>();
    private RecyclerView mRvStatus;
    private ScreenAdapter statusAdapter;
    private final List<TabBean> tabBeanList = new ArrayList<>();
    private TextView mTvReset;
    private TextView mTvConfirm;
    private ScreenAdapter lineAdapter;
    private BaseFragment baseFragment;
    private BaseActivity baseActivity;
    private ScreenListener screenListener;
    private Context context;

    public ScreenDialog(@NonNull BaseFragment context) {
        super(context.getContext(), R.style.MyBottomDialogStyle);
        baseFragment = context;
        this.context = baseFragment.getContext();
    }

    public ScreenDialog(@NonNull BaseActivity context) {
        super(context, R.style.MyBottomDialogStyle);
        baseActivity = context;
        this.context = context;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_screen);
        Window window = getWindow();
        //底部弹出的Dialog
        window.setGravity(Gravity.BOTTOM);
        //设置动画
        window.setWindowAnimations(R.style.main_menu_animstyle);
        WindowManager.LayoutParams attributes = window.getAttributes();

        //保证按钮水平满屏
        attributes.width = ViewGroup.LayoutParams.MATCH_PARENT;
        attributes.height = MyUtils.getScreenHeight(getContext()) * 7 / 10;

        //设置显示位置
        window.setAttributes(attributes); //将属性设置给窗体
        initView();
        tabBeanList.add(new TabBean("待付款", "0"));
        tabBeanList.add(new TabBean("待揽收", "5"));
        tabBeanList.add(new TabBean("已入库", "7"));
        tabBeanList.add(new TabBean("运输中", "9"));
        tabBeanList.add(new TabBean("待签收", "11"));
        tabBeanList.add(new TabBean("有回单", "101"));
        tabBeanList.add(new TabBean("已完成", "15,20"));
        tabBeanList.add(new TabBean("已取消", "99"));
        tabBeanList.add(new TabBean("全部", ""));

        typeList.add(new TabBean("全部", ""));
        typeList.add(new TabBean("极速", ""));
        typeList.add(new TabBean("指派", ""));
        typeList.add(new TabBean("实时单", ""));
        typeList.add(new TabBean("预约单", ""));
        typeList.add(new TabBean("快运", ""));
        typeList.add(new TabBean("普运", ""));

        lineAdapter = new ScreenAdapter();
        mRvLine.setAdapter(lineAdapter);
        mRvLine.setLayoutManager(new AutoLineFeedLayoutManager());

        statusAdapter = new ScreenAdapter(tabBeanList);
        mRvStatus.setLayoutManager(new AutoLineFeedLayoutManager());
        mRvStatus.setAdapter(statusAdapter);

        typeAdapter = new ScreenAdapter(typeList);
        mRvType.setAdapter(typeAdapter);
        mRvType.setLayoutManager(new AutoLineFeedLayoutManager());
        initData();
    }

    @SuppressLint("NotifyDataSetChanged")
    private void initData() {
        lineAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {

            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                for (TabBean datum : lineAdapter.getData()) {
                    datum.setChecked(false);
                }
                lineAdapter.getData().get(position).setChecked(true);
                lineAdapter.notifyDataSetChanged();
            }
        });
        statusAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (statusAdapter.isHaveChoice) {
                    for (TabBean tabBean : tabBeanList) {
                        tabBean.setChecked(false);
                    }
                    tabBeanList.get(position).setChecked(true);
                    statusAdapter.notifyDataSetChanged();
                } else {
                    ToastUtil.show("不可选");
                }
            }
        });

        typeAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                for (TabBean tabBean : typeList) {
                    tabBean.setChecked(false);
                }
                typeList.get(position).setChecked(true);
                typeAdapter.notifyDataSetChanged();
            }
        });
        if (baseFragment != null) {
            baseFragment.networkRequest(baseFragment.netApi.getSpecialList(1, 20), this);
        } else {
            baseActivity.networkRequest(baseActivity.netApi.getSpecialList(1, 20), this);
        }
    }

//    @Override
//    protected int getImplLayoutId() {
//        return R.layout.dialog_screen;
//    }
//
//    @Override
//    protected int getMaxHeight() {
//        return MyUtils.getScreenHeight(getContext()) * 8 / 10;
//    }

    private void initView() {
        mLlScreen = findViewById(R.id.ll_screen);
        mLlTime = findViewById(R.id.ll_time);
        mTvStartTime = findViewById(R.id.tv_start_time);
        mTvEndTime = findViewById(R.id.tv_end_time);
        mRvLine = findViewById(R.id.rv_line);
        mRvType = findViewById(R.id.rv_type);
        mRvStatus = findViewById(R.id.rv_status);
        mTvReset = findViewById(R.id.tv_reset);
        mTvConfirm = findViewById(R.id.tv_confirm);
        findViewById(R.id.fl_close).setOnClickListener(this);
        mTvStartTime.setOnClickListener(this);
        mTvEndTime.setOnClickListener(this);
        mTvConfirm.setOnClickListener(this);
        mTvReset.setOnClickListener(this);
    }

    @SuppressLint("NotifyDataSetChanged")
    public void getSelectedTabPosition(int position) {
        statusAdapter.isHaveChoice = position == 0;
        statusAdapter.notifyDataSetChanged();
        if (position == 0) {
            return;
        }
        for (TabBean tabBean : tabBeanList) {
            tabBean.setChecked(false);
        }
        tabBeanList.get(position - 1).setChecked(true);

    }


    @Override
    public void onResponse(int requestCode, String json, Response<ResponseBody> response) throws Exception {
        DedicatedLineDataBean bean = new Gson().fromJson(json, DedicatedLineDataBean.class);
        if (bean.isStatus()) {
            List<TabBean> lineList = new ArrayList<>();
            for (DedicatedLineBean data : bean.getData().getList()) {
                String start_city = data.getStart_city().replace("市", "");
                String end_city = data.getEnd_city().replace("市", "");
                lineList.add(new TabBean(String.format("%s-%s", start_city, end_city), String.valueOf(data.getLine_id())));
            }
            lineAdapter.setNewData(lineList);
        }
    }

    @Override
    public void onFailure(int requestCode) {

    }

    public void setMyClickListener(@Nullable ScreenListener l) {
        this.screenListener = l;
    }

    private int timeType;

    @SuppressLint("NotifyDataSetChanged")
    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.tv_start_time) {
            DatePickerDialogShow(1);
        } else if (view.getId() == R.id.tv_end_time) {
            DatePickerDialogShow(2);
        } else if (view.getId() == R.id.tv_reset) {
            mTvStartTime.setText("");
            mTvEndTime.setText("");
            for (TabBean datum : lineAdapter.getData()) {
                datum.setChecked(false);
            }
            for (TabBean tabBean : typeList) {
                tabBean.setChecked(false);
            }
            if (statusAdapter.isHaveChoice) {
                for (TabBean tabBean : tabBeanList) {
                    tabBean.setChecked(false);
                }
                statusAdapter.notifyDataSetChanged();
            }
            lineAdapter.notifyDataSetChanged();
            typeAdapter.notifyDataSetChanged();
        } else if (view.getId() == R.id.tv_confirm) {
            dismiss();
            confirm();
        } else if (view.getId() == R.id.fl_close) {
            dismiss();
        }
    }

    private void confirm() {
        String lineId = "";
        String type = "";
        String status = "";
        for (TabBean datum : lineAdapter.getData()) {
            if (datum.isChecked()) {
                lineId = datum.getType();
            }
        }
        for (TabBean tabBean : typeList) {
            if (tabBean.isChecked()) {
                type = tabBean.getTypeName();
            }
        }
        for (TabBean tabBean : tabBeanList) {
            if (tabBean.isChecked()) {
                status = tabBean.getType();
            }
        }
        screenListener.onClick(new ScreenEvent(mTvStartTime.getText().toString(), mTvEndTime.getText().toString(), lineId, type, status));
    }

    private void DatePickerDialogShow(int type) {
        String title;
        if (timeType == 1) {
            title = "设置开始时间";
        } else {
            title = "设置结束时间";
        }
        new CardDatePickerDialog.Builder(context)
                .setTitle(title)
                .showBackNow(false)
                .setDisplayType(DateTimeConfig.YEAR, DateTimeConfig.MONTH, DateTimeConfig.DAY)
                .setThemeColor(Color.parseColor("#485EF4"))
                .setOnChoose("确定", aLong -> {
                    if (timeType == 1) {
                        mTvStartTime.setText(DateUtils.getYearMonthDay(aLong));
                    } else {
                        mTvEndTime.setText(DateUtils.getYearMonthDay(aLong));
                    }
                    return null;
                }).build().show();
        timeType = type;
    }


}
